using System.Collections.Generic;
using System.Linq;
using Unity.VisualScripting;
using UnityEngine;

namespace M0
{
    public class Mono缓存池 : BaseSingleMono<Mono缓存池>
    {
        private Dictionary<string, List<Object>> 加载缓存 = new Dictionary<string, List<Object>>();
        [SerializeField]private Transform 容身之地;

        public T F创建<T>(string key, T 模板,Transform tran) where T: Object
        {
            if (加载缓存.ContainsKey(key) && 加载缓存[key].Count>0)
            {
                var 第一个 = 加载缓存[key][0];
                加载缓存[key].RemoveAt(0);
                Show(第一个, tran);
                return 第一个 as T;
            }

            var copy = Instantiate(模板, tran);
            return copy;
        }

        public void F回收(string key, Object o)
        {
            if (加载缓存.ContainsKey(key))
            {
                if (!加载缓存[key].Any(a => a == o))
                {
                    加载缓存[key].Add(o);  
                }
            }
            else
            {
                加载缓存.Add(key,new List<Object>(){o});
            }
            var obj = o.GameObject();
            obj.SetActive(false);
            obj.transform.SetParent(容身之地,false);
        }

        private void Show(Object o,Transform tran)
        {
            var obj = o.GameObject();
            if (tran != null)
            {
                obj.transform.SetParent(tran,false);
            }
            obj.gameObject.SetActive(true);
        }
    }

}
